<?php

namespace App\Http\Controllers\Api;

use App\Enums\OrderStatus;
use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\Channel;
use App\Models\FrontendUser;
use App\Models\Order;
use DB;

class ChannelController extends Controller
{
    /** 查询渠道详情 */
    public function getChannel($id)
    {
        $channel = $this->findChannel($id);
        $result = [
            'cover_image_url' => $channel->cover_image_url ?: '',
            'code' => $channel->uuid,
        ];
        //查询邀请人数和成交金额
        $orderSummary = DB::selectOne("SELECT sum(order_amount) AS order_amount FROM op_orders AS a INNER JOIN op_frontend_users AS c ON a.user_id = c.id WHERE a.order_status = 'paid' AND c.channel_id = {$id}");
        $userSummary = DB::selectOne("SELECT count(a.id)as user_count, COUNT(b.id) as real_user_count FROM op_frontend_users AS a LEFT JOIN op_user_auths AS b ON a.id = b.user_id WHERE a.channel_id = {$id}");

        $result['summary'] = [
            'order_amount' => toYuan($orderSummary->order_amount),
            'user_count' => $userSummary->user_count,
            'real_user_count' => $userSummary->real_user_count,
        ];

        return $result;
    }

    /** 查询渠道用户 */
    public function listChannelUsers($id)
    {
        $page = request()->get('page', 1);
        $limit = request()->get('limit', 10);
        $realOnly = 1 == request()->get('real_only', 0);
        $channel = $this->findChannel($id);
        $query = FrontendUser::query()
            ->with(['auth'])
            ->when($realOnly, function ($q) {
                return $q->whereHas('auth');
            })
            ->where('channel_id', $channel->id);

        $count = $query->count();
        $list = $query->limit($limit)->offset(($page - 1) * $limit)
            ->orderByDesc('id')
            ->get()->map(function (FrontendUser $user) {
                return [
                    'mobile' => hide_mobile($user->mobile),
                    'created_at' => $user->created_at ? $user->created_at->toDateTimeString() : '',
                    'is_real' => (bool) $user->auth,
                ];
            });

        return [
            'list' => $list,
            'count' => $count,
        ];
    }

    /** 查询月度订单汇总 */
    public function listOrderMonthSummaries($id)
    {
        $this->findChannel($id);

        return Order::query()
            ->selectRaw('YEAR(created_at) as year, MONTH(created_at) as month, count(*) as count, sum(order_amount) as amount')
            ->where('order_status', OrderStatus::PAID)
            ->whereHas('user', function ($q) use ($id) {
                return $q->where('channel_id', $id);
            })
            ->groupBy(['year', 'month'])
            ->orderByDesc('year')->orderByDesc('month')
            ->get()
            ->map(function (Order $order) {
                return [
                    'year' => $order->year,
                    'month' => $order->month,
                    'count' => $order->count,
                    'amount' => toYuan($order->amount),
                ];
            });
    }

    /** 查询订单明细 */
    public function listOrders($id)
    {
        $this->findChannel($id);
        $query = Order::query()
            ->where('order_status', OrderStatus::PAID)
            ->whereHas('user', function ($q) use ($id) {
                return $q->where('channel_id', $id);
            })
            ->when(request()->year, function ($q) {
                return $q->whereYear('created_at', request()->year);
            })
            ->when(request()->month, function ($q) {
                return $q->whereMonth('created_at', request()->month);
            });

        $count = $query->count();
        $page = request()->get('page', 1);
        $limit = request()->get('limit', 10);
        $list = $query
            ->with(['product', 'user'])
            ->offset(($page - 1) * $limit)->limit($limit)->orderByDesc('id')
            ->get()->map(function (Order $order) {
                return [
                    'product_name' => $order->product->name,
                    'product_logo_url' => $order->product->logo_url,
                    'order_no' => $order->order_no,
                    'order_amount' => $order->display_order_amount,
                    'user_mobile' => hide_mobile($order->user->mobile),
                    'created_at' => $order->created_at->toDateTimeString(),
                ];
            });

        return [
            'count' => $count,
            'list' => $list,
        ];
    }

    /**
     * @param $channelId
     *
     * @return Channel
     */
    private function findChannel($channelId)
    {
        /** @var FrontendUser $user */
        $user = auth()->user();
        $channel = Channel::query()
            ->where('agent_id', request()->agent_id)
            ->where('mobile', $user->mobile)
            ->find($channelId);
        if (!$channel) {
            throw new ApiException('无效的渠道ID');
        }

        return $channel;
    }
}
